package com.yuhs.zixing.pay.dal.base.page;

import java.io.Serializable;

/**
 * @ClassName PageQuery
 * @Description 分页查询
 * @Author yuhs
 * @CreateDate 2020/12/6
 **/
public class PageQuery implements Serializable {

    /**
     * 默认每页显示的记录数
     */
    public static final int DEFAULT_PAGE_SIZE = 20;
    /**
     * 最大每页显示的记录数
     */
    public static final int MAX_PAGE_SIZE = 200;
    /**
     * 默认每页显示的记录数
     */
    public static final int DEFAULT_PAGE_NUMBER = 1;

    private int page;
    private int limit;
    private boolean lockedOffset;
    private int offset;

    public PageQuery() {
        this.limit = DEFAULT_PAGE_SIZE;
        this.page = DEFAULT_PAGE_NUMBER;
    }

    public PageQuery(int page, int limit) {
        if (page < 1) {
            throw new IllegalArgumentException("Page index must not be less than one!");
        }

        if (limit < 1) {
            throw new IllegalArgumentException("Page size must not be less than one!");
        }

        this.page = page;
        this.limit = limit > MAX_PAGE_SIZE ? MAX_PAGE_SIZE : limit;
    }

    public void lockOffset() {
        lockedOffset = true;
        this.offset = (page - 1) * limit;
    }

    public void unlockOffset() {
        lockedOffset = false;
    }


    public int getOffset() {
        if (lockedOffset) {
            return offset;
        }
        return (page - 1) * limit;
    }

    @Override
    public String toString() {
        return "PageQuery{" +
                "page=" + page +
                ", limit=" + limit +
                '}';
    }


    /**
     * 获取每页可显示的记录数
     *
     * @return 每页可显示的记录数
     */
    public int getPage() {
        return page;
    }

    /**
     * 设置页号
     *
     * @param page 页号
     */
    public void setPage(int page) {
        if (page < 1) {
            throw new IllegalArgumentException("Page index must not be less than one!");
        }
        this.page = page;
    }

    /**
     * 获取每页可显示的记录数
     *
     * @return
     */
    public int getLimit() {
        return limit;
    }

    /**
     * 设置每页可现实的记录数
     *
     * @param limit 每页可现实的记录数
     */
    public void setLimit(int limit) {
        if (limit < 1) {
            throw new IllegalArgumentException("Page size must not be less than one!");
        }
        this.limit = limit > MAX_PAGE_SIZE ? MAX_PAGE_SIZE : limit;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }
}
